package com.pengshun.modules.api.transport.service.impl;

import com.pengshun.modules.aliyun.OosPush;
import com.pengshun.modules.api.coal.repository.MerchantRepository;
import com.pengshun.modules.api.coal.repository.UserRepository;
import com.pengshun.modules.api.coal.util.CommonUtil;
import com.pengshun.modules.api.mapper.PsUserInComRecordMapper;
import com.pengshun.modules.api.mapper.TransportAbnormalOperationMapper;
import com.pengshun.modules.api.mapper.TransportMapper;
import com.pengshun.modules.api.order.service.dto.IncomeRecordDto;
import com.pengshun.modules.api.order.service.mapstruct.IncomeRecordTodo;
import com.pengshun.modules.api.pay.service.WechatPayService;
import com.pengshun.modules.api.transport.dto.FreightSettlementDto;
import com.pengshun.modules.api.transport.dto.FreightSettlementPhotoDto;
import com.pengshun.modules.api.transport.dto.TransportAbnormalOperationDto;
import com.pengshun.modules.api.transport.repository.*;
import com.pengshun.modules.api.transport.service.mapstruct.FreightSettlementPhotoTodo;
import com.pengshun.modules.api.transport.service.mapstruct.FreightSettlementTodo;
import com.pengshun.modules.api.transport.service.mapstruct.TransportAbnormalOperationlTodo;
import com.pengshun.modules.api.user.repository.IncomeRecordRepository;
import com.pengshun.modules.api.user.repository.IncomeRepository;
import com.pengshun.modules.common.BillType;
import com.pengshun.modules.common.OrderCommon;
import com.pengshun.modules.common.PagePara;
import com.pengshun.modules.api.transport.dto.SettlementDto;
import com.pengshun.modules.api.transport.service.FreightSettlementService;
import com.pengshun.modules.common.BaseResult;
import com.pengshun.modules.domain.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@Service
@RequiredArgsConstructor
public class FreightSettlementServiceImpl implements FreightSettlementService {


    private final TransportMapper transportMapper;

    private final TransportTakeCarriageRepository transportTakeCarriageRepository;

    private final FreightSettlementRepository freightSettlementRepository;
    private final FreightSettlementPriceRepository freightSettlementPriceRepository;

    private final FreightSettlementTodo freightSettlementTodo;

    private final UserRepository userRepository;

    private final FreightSettlementPhotoRepository freightSettlementPhotoRepository;

    private final FreightSettlementPhotoTodo freightSettlementPhotoTodo;

    private final MerchantRepository merchantRepository;

    private final MessageSource messageSource;

    private final TransportTakeOrderRepository transportTakeOrderRepository;

    private final WechatPayService wechatPayService;

    private final IncomeRepository incomeRepository;

    private final IncomeRecordRepository incomeRecordRepository;

    private final IncomeRecordTodo incomeRecordTodo;

    private final SettlementPayRecordRepository settlementPayRecordRepository;

    private final PsUserInComRecordMapper uirm;

    private final TransportRepository transportRepository;
    private final TransportAbnormalRepository transportAbnormalRepository;
    private final TransportAbnormalOperationRepository transportAbnormalOperationRepository;
    private final TransportAbnormalOperationlTodo transportAbnormalOperationlTodo;
    private final TransportAbnormalOperationMapper transportAbnormalOperationMapper;
    private final TransportTakeStatusRepository transportTakeStatusRepository;

    @Override
    public BaseResult driverList(PagePara para) {
        List<SettlementDto> list = transportMapper.driverFreightSettlementList(para.getPage(), para.getSize(), para.getStatus(), para.getUserId());
        return new BaseResult(0, list);
    }

    @Override
    public BaseResult transportList(PagePara para) {
        //商户带结算查询订单id为空的 不为空 平台审核
        List<SettlementDto> list = transportMapper.transporFreightSettlementList(para.getPage(), para.getSize(), para.getStatus(), para.getUserId());
        return new BaseResult(0, list);
    }

    @Override
    public BaseResult transportDetil(Long freightSettlementId) {
        //查询结算单详情
        FreightSettlement settlement = freightSettlementRepository.findById(freightSettlementId).orElseGet(FreightSettlement::new);
        //查询结算单据
        List<FreightSettlementPhoto> photos = freightSettlementPhotoRepository.findByFreightSettlementId(freightSettlementId);
        //查询支付记录
        SettlementPayRecord record = settlementPayRecordRepository.findByFreightSettlementId(freightSettlementId);

        //实体类转换
        FreightSettlementDto dto = freightSettlementTodo.toDto(settlement);
        dto.setPhotos(photos);
        if (record != null) {
            dto.setPayWay(record.getPayWay());
        }
        return new BaseResult(0, dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult save(FreightSettlementDto para) throws Exception {
        //查询运单详情
        TransportTakeCarriage carriage = transportTakeCarriageRepository.findById(para.getTransportTakeCarriageId()).orElseGet(TransportTakeCarriage::new);
        //矿发实收吨位不能大于接取吨位
        if(para.getMineSendNum().compareTo(carriage.getNumber())==1){
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.save.numbers.err", null, Locale.CHINA));
        }
        if(para.getRealNum().compareTo(carriage.getNumber())==1){
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.save.number.err", null, Locale.CHINA));
        }

        //判断是否申请结算过
        if (carriage.getIsApply() == 1) {
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.save.exist", null, Locale.CHINA));
        }
        FreightSettlement settlement = freightSettlementRepository.findByTransportTakeCarriageId(para.getTransportTakeCarriageId());
        if (settlement != null) {
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.save.exist", null, Locale.CHINA));
        }
        //当实收吨位大于矿发吨位时则以矿发吨位结算，两者取其小
        BigDecimal realNum=para.getRealNum().compareTo(para.getMineSendNum())==1?para.getMineSendNum():para.getRealNum();
        //计算费用是否准确  最终数量乘以运费
        para.setOtherFee(para.getOtherFee() == null ? new BigDecimal(0) : para.getOtherFee());
        BigDecimal totalFee = (realNum.multiply(carriage.getFreight()));
        if (totalFee.compareTo(para.getSettlementAmount()) != 0) {
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.save.price.error", null, Locale.CHINA));
        }
        //更新接单表申请状态
        carriage.setIsApply(1);
        transportTakeCarriageRepository.save(carriage);
        //结算表添加数据
        para.setFreight(carriage.getFreight());
        para.setLoadFee(carriage.getLoadFee());
        para.setUnloadFee(carriage.getUnloadFee());
        para.setPoundsFee(carriage.getPoundsFee());
        para.setOtherFee(carriage.getOtherFee());
        //查询用户信息 设置电话姓名
        User user = userRepository.findById(para.getApplyUserId()).orElseGet(User::new);
        para.setApplyUserPhone(user.getPhone());
        para.setApplyUserName(user.getName());
        para.setStatus(1);
        para.setApplyDate(new Date());

        //查询接单详情
        TransportTakeOrder takeOrder = transportTakeOrderRepository.findById(carriage.getTransportTakeOrderId()).orElseGet(TransportTakeOrder::new);
        para.setGatheringUserId(takeOrder.getGatheringUserId());
        para.setSettlementNo("PS" + CommonUtil.getFourRandom());
        para.setTransportId(takeOrder.getTransportId());
        para.setOrderId(takeOrder.getOrderId());
        para.setSettlementType(takeOrder.getOrderId() == null ? 2 : 1);
        //根据商户id  查询支付用户id
        Transport transport = transportRepository.findById(takeOrder.getTransportId()).orElseGet(Transport::new);
        para.setPayUserId(transport.getUserId());
        para.setMerchantName(transport.getMerchantName());
        FreightSettlement freights = freightSettlementTodo.toEntity(para);
        freights.setSettlementType(para.getSettlementType());
        freights.setOrderId(carriage.getOrderId());
        FreightSettlement freightSettlement = freightSettlementRepository.save(freights);
        //结算票据表添加图片信息
        List<FreightSettlementPhotoDto> photoDtos = new ArrayList<>();
        String urls[] = para.getUrls().split(",");
        for (int i = 0; i < urls.length; i++) {
            FreightSettlementPhotoDto dto = new FreightSettlementPhotoDto(freightSettlement.getFreightSettlementId(), urls[i]);
            photoDtos.add(dto);
        }
        freightSettlementPhotoRepository.saveAll(freightSettlementPhotoTodo.toEntity(photoDtos));
        return new BaseResult(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult update(FreightSettlementDto para) throws Exception {
        //查询结算单详情
        FreightSettlement settlement = freightSettlementRepository.findById(para.getFreightSettlementId()).orElse(null);
        //判断状态防止误操作
        if (settlement == null) {
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.update.notexist", null, Locale.CHINA));
        }
        if (settlement.getStatus() != 2) {
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.update.status.error", null, Locale.CHINA));
        }
        //查询运单详情
        TransportTakeCarriage carriage = transportTakeCarriageRepository.findById(settlement.getTransportTakeCarriageId()).orElseGet(TransportTakeCarriage::new);
        //矿发实收吨位不能大于接取吨位
        BigDecimal num= new BigDecimal(150);
        if(para.getMineSendNum().compareTo(num)==1){
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.save.numbers.big.err", null, Locale.CHINA));
        }
        if(para.getRealNum().compareTo(num)==1){
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.save.numbers.real.big.err", null, Locale.CHINA));
        }
        para.setOtherFee(para.getOtherFee() == null ? new BigDecimal(0) : para.getOtherFee());
        //计算结算金额
        BigDecimal last=para.getMineSendNum();
        if(para.getMineSendNum().compareTo(para.getRealNum())==1){
            last=para.getRealNum();
        }
        //计算费用是否准确  最终数量乘以运费 -其他费用- 差异费用
        BigDecimal totalFee = last.multiply(carriage.getFreight());
        totalFee=totalFee.subtract(settlement.getOtherFee());
        BigDecimal diffPrice=new BigDecimal(0);
        if(para.getDiffNum().compareTo(BigDecimal.ZERO)==1){
            diffPrice=para.getDiffNum().multiply(settlement.getPrice());
            totalFee=totalFee.subtract(diffPrice);
        }
        if (totalFee.compareTo(para.getSettlementAmount()) != 0) {
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.save.price.error", null, Locale.CHINA));
        }
        settlement.setDiffPrice(diffPrice);
        settlement.setStatus(1);
        settlement.setMineSendNum(para.getMineSendNum());
        settlement.setRealNum(para.getRealNum());
        settlement.setDiffNum(para.getDiffNum());
        settlement.setSettlementAmount(totalFee);
        settlement.setOtherFee(para.getOtherFee());
        settlement.setRemark(para.getRemark());
        if(settlement.getSettlementAmount().compareTo(BigDecimal.ZERO)==-1){
            settlement.setIsAbnormal("1");
            settlement.setAbnormalStatus("1");
        }else {
            settlement.setIsAbnormal("0");

        }
        settlement.setApplyDate(new Date());
//        if(settlement.getCashProportion()>settlement.getOilProportion()){
//            int oilFee=(settlement.getSettlementAmount().divide(new BigDecimal(settlement.getOilProportion())).setScale( 0, BigDecimal.ROUND_UP ).intValue());
//            settlement.setOilCardFee(new BigDecimal(oilFee));
//            settlement.setCashFee(settlement.getSettlementAmount().subtract(settlement.getOilCardFee()));
//        }else{
//            int cashFee=(settlement.getSettlementAmount().divide(new BigDecimal(settlement.getCashProportion())).setScale( 0, BigDecimal.ROUND_UP ).intValue());
//            settlement.setCashFee(new BigDecimal(cashFee));
//            settlement.setOilCardFee(settlement.getSettlementAmount().subtract(settlement.getCashFee()));
//        }
        //修改保存
        freightSettlementRepository.save(settlement);
        //删除之前票据  重新保存
        freightSettlementPhotoRepository.deleteByFreightSettlementId(para.getFreightSettlementId());
        //结算票据表添加图片信息
        List<FreightSettlementPhotoDto> photoDtos = new ArrayList<>();
        String urls[] = para.getUrls().split(",");
        for (int i = 0; i < urls.length; i++) {
            FreightSettlementPhotoDto dto = new FreightSettlementPhotoDto(para.getFreightSettlementId(), urls[i]);
            photoDtos.add(dto);
        }
        freightSettlementPhotoRepository.saveAll(freightSettlementPhotoTodo.toEntity(photoDtos));
        return new BaseResult(0);
    }

    @Override
    public BaseResult back(FreightSettlementDto para) {
        FreightSettlement settlement = freightSettlementRepository.findById(para.getFreightSettlementId()).orElse(null);
        if (settlement.getStatus() != 1) {
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.update.status.error", null, Locale.CHINA));
        }
        settlement.setStatus(2);
        settlement.setRejectTime(new Date());
        settlement.setCasue(para.getCasue());
        settlement.setIsAbnormal("0");
        freightSettlementRepository.save(settlement);
        //流程更新
        TransportTakeStatus status=transportTakeStatusRepository.findByTransportTakeCarriageId(settlement.getTransportTakeCarriageId());
        status.setBackTime(new Date());
        transportTakeStatusRepository.save(status);
        return new BaseResult(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult pay(FreightSettlementDto para) throws Exception {
        //查询结算单信息
        FreightSettlement settlement = freightSettlementRepository.findById(para.getFreightSettlementId()).orElse(null);
        //判断订单状态 防止多次操作
        if (settlement.getStatus() != 1) {
            return new BaseResult(1, "重复提交数据");
        }
        if(settlement.getCheckStatus()!=2){
            return new BaseResult(1, "未审核不能发放");
        }
        //流程更新
        TransportTakeStatus status=transportTakeStatusRepository.findByTransportTakeCarriageId(settlement.getTransportTakeCarriageId());
        if (para.getPayWay().equals(OrderCommon.PAY_WAY_ONE)) {
            //余额支付
            if (para.getPayPass() == null) {
                return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.pay.payPss.null", null, Locale.CHINA));
            }
            //验证支付密码是否正确
            User users = userRepository.findById(para.getUserId()).orElseGet(User::new);
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            if (!bCryptPasswordEncoder.matches(para.getPayPass(), users.getPayPass())) {
                return new BaseResult(5, messageSource.getMessage("FreightSettlementServiceImpl.pay.payPss.error", null, Locale.CHINA));
            }
            if (!users.getEnabled()) {
                //说明用户被禁用
                return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.pay.user.getEnabled", null, Locale.CHINA));
            }
            //判断账户余额
            Income income = incomeRepository.findByUserId(para.getUserId());
            BigDecimal needPayMoney = settlement.getSettlementAmount();
            //判断余额是否足够
            if (income.getUsableBlanace().compareTo(needPayMoney) == -1) {
                return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.pay.getUsableBlanace", null, Locale.CHINA));
            }
            User payUser = userRepository.findById(settlement.getGatheringUserId()).orElseGet(User::new);
            //结算支付记录表添加数据
            SettlementPayRecord record = settlementPayRecordRepository.save(new SettlementPayRecord(settlement.getFreightSettlementId(), OrderCommon.PAY_WAY_ONE, needPayMoney, para.getUserId(), new Date()));
            //更新结算单状态为已结算
            settlement.setStatus(3);
            settlement.setCleanDate(new Date());
            freightSettlementRepository.save(settlement);
            //更新商户账户余额
            BigDecimal nowBlanace = income.getUsableBlanace().subtract(needPayMoney);
            BigDecimal userNowAccountBlanace = income.getAccountBlanace().subtract(needPayMoney);
            uirm.updateBlanace(income.getUsableBlanace(), nowBlanace, para.getUserId(), income.getAccountBlanace(), userNowAccountBlanace);
            //商户账单表添加数据
            String billNo = settlement.getSettlementNo();
            String remark = "余额支付运费";

            IncomeRecordDto incomeRecord = new IncomeRecordDto(para.getUserId(), billNo, needPayMoney, OrderCommon.PAYMENT_TYPE_TWO, OrderCommon.BILL_TYPE_TWO, settlement.getFreightSettlementId(),
                    OrderCommon.PAY_WAY_ONE, remark, 1, new Date(), 1,payUser.getName(),payUser.getAvatarName(),settlement.getTransportTakeCarriageId());
            incomeRecordRepository.save(incomeRecordTodo.toEntity(incomeRecord));

            //更新用户余额
            Income userIncome = incomeRepository.findByUserId(settlement.getGatheringUserId());
            BigDecimal userNowBlanace = userIncome.getUsableBlanace().add(needPayMoney);
            BigDecimal userNowAccountBlanaces = userIncome.getAccountBlanace().add(needPayMoney);
            uirm.updateBlanace(userIncome.getUsableBlanace(), userNowBlanace, settlement.getGatheringUserId(), userIncome.getAccountBlanace(), userNowAccountBlanaces);
            //待结算用户账单表添加数据
            Merchant merchant=merchantRepository.findByUserId(settlement.getPayUserId());
            IncomeRecordDto userIncomeRecord = new IncomeRecordDto(settlement.getGatheringUserId(), billNo, needPayMoney, OrderCommon.BPAYMENT_TYPE_ONE, OrderCommon.BILL_TYPE_FOUR, settlement.getFreightSettlementId(),
                    OrderCommon.PAY_WAY_ONE, "运费收入", 1, new Date(), 1,merchant.getName(),merchant.getDoorImg(),settlement.getTransportTakeCarriageId());
            incomeRecordRepository.save(incomeRecordTodo.toEntity(userIncomeRecord));

            //更新运单结算状态
            TransportTakeCarriage carriage = transportTakeCarriageRepository.findById(settlement.getTransportTakeCarriageId()).orElseGet(TransportTakeCarriage::new);
            carriage.setCleanStatus(2);
            transportTakeCarriageRepository.save(carriage);
            //商户通知
            OosPush.push("付款通知", "您的账户支出" + needPayMoney + "元", "ALIAS", users.getAlias());
            //用户通知
            OosPush.push("到账通知", "您的账户收入" + needPayMoney + "元", "ALIAS", payUser.getAlias());
            status.setSettlementTime(new Date());
            transportTakeStatusRepository.save(status);
            return new BaseResult(0,messageSource.getMessage("sure.success", null, Locale.CHINA),carriage,false);
        } else if (para.getPayWay().equals(OrderCommon.PAY_WAY_TWO)) {
            //微信支付
            String attach = para.getUserId() + "-" + BillType.BILL_TYPE_TWO + "-" + para.getFreightSettlementId();
            Integer waitPayMoney = settlement.getSettlementAmount().multiply(new BigDecimal(100)).intValue();
            status.setSettlementTime(new Date());
            transportTakeStatusRepository.save(status);
            return new BaseResult(0, wechatPayService.unifiedorder("运输公司运费结算", waitPayMoney, attach, "APP", ""));
        }

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult sure(FreightSettlementDto para) throws Exception {
        //查询结算单信息
        FreightSettlement settlement = freightSettlementRepository.findById(para.getFreightSettlementId()).orElse(null);
        //判断订单状态 防止多次操作
        if (settlement.getStatus() != 1) {
            return new BaseResult(1, "重复提交数据");
        }
        //验证支付密码是否正确
        User users = userRepository.findById(para.getUserId()).orElseGet(User::new);
        if (!users.getEnabled()) {
            //说明用户被禁用
            return new BaseResult(1, messageSource.getMessage("FreightSettlementServiceImpl.pay.user.getEnabled", null, Locale.CHINA));
        }
        //判断账户余额
        BigDecimal needPayMoney = settlement.getSettlementAmount();
        //结算支付记录表添加数据
        SettlementPayRecord record = settlementPayRecordRepository.save(new SettlementPayRecord(settlement.getFreightSettlementId(), OrderCommon.PAY_WAY_FIVE, needPayMoney, para.getUserId(), new Date()));
        //更新结算单状态为已结算
        settlement.setStatus(3);
        settlement.setCleanDate(new Date());
        freightSettlementRepository.save(settlement);
        String billNo = settlement.getSettlementNo();
        //更新用户余额
        Income userIncome = incomeRepository.findByUserId(settlement.getGatheringUserId());
        BigDecimal userNowBlanace = userIncome.getUsableBlanace().add(needPayMoney);
        BigDecimal userNowAccountBlanaces = userIncome.getAccountBlanace().add(needPayMoney);
        uirm.updateBlanace(userIncome.getUsableBlanace(), userNowBlanace, settlement.getGatheringUserId(), userIncome.getAccountBlanace(), userNowAccountBlanaces);
        //待结算用户账单表添加数据
        Merchant merchant=merchantRepository.findByUserId(settlement.getPayUserId());
        IncomeRecordDto userIncomeRecord = new IncomeRecordDto(settlement.getGatheringUserId(), billNo, needPayMoney, OrderCommon.BPAYMENT_TYPE_ONE, OrderCommon.BILL_TYPE_FOUR, settlement.getFreightSettlementId(),
                OrderCommon.PAY_WAY_ONE, "运费收入", 1, new Date(), 1,merchant.getName(),merchant.getDoorImg(),settlement.getTransportTakeCarriageId());
        incomeRecordRepository.save(incomeRecordTodo.toEntity(userIncomeRecord));

        //更新运单结算状态
        TransportTakeCarriage carriage = transportTakeCarriageRepository.findById(settlement.getTransportTakeCarriageId()).orElseGet(TransportTakeCarriage::new);
        carriage.setCleanStatus(2);
        transportTakeCarriageRepository.save(carriage);
        //商户通知
//        OosPush.push("付款通知","您的账户支出"+needPayMoney+"元","ALIAS", users.getAlias());
        //用户通知
        User payUser = userRepository.findById(settlement.getGatheringUserId()).orElseGet(User::new);
        OosPush.push("到账通知", "您的账户收入" + needPayMoney + "元", "ALIAS", payUser.getAlias());
        return new BaseResult(0,messageSource.getMessage("sure.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult driverAbnormalList(PagePara para) {
        List<SettlementDto> list = transportMapper.driverAbnormalList(para.getPage(), para.getSize(), para.getStatus(), para.getUserId());
        return new BaseResult(0, list);
    }

    @Override
    public BaseResult transportAbnormalList(PagePara para) {
        List<SettlementDto> list = transportMapper.transportAbnormalList(para.getPage(), para.getSize(), para.getStatus(), para.getUserId());
        return new BaseResult(0, list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult driverAbnormalApply(TransportAbnormalOperationDto para) {
        para.setStatus("1");
        para.setCreateTime(new Date());
        TransportAbnormalOperation operation=transportAbnormalOperationRepository.save(transportAbnormalOperationlTodo.toEntity(para));
        for (TransportAbnormal ph : para.getPhotos()) {
            ph.setTransportAbnormalOperationId(operation.getTransportAbnormalOperationId());

        }
        //更新结算表状态
        FreightSettlement settlement=freightSettlementRepository.findById(para.getFreightSettlementId()).orElseGet(FreightSettlement::new);
        settlement.setAbnormalStatus("2");
        freightSettlementRepository.save(settlement);
        //证据表添加数据
        transportAbnormalRepository.saveAll(para.getPhotos());
        //流程更新
        TransportTakeStatus status=transportTakeStatusRepository.findByTransportTakeCarriageId(settlement.getTransportTakeCarriageId());
        status.setExpTime(new Date());
        transportTakeStatusRepository.save(status);

        return new BaseResult(0,messageSource.getMessage("operation.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult AbnormalApplyDetil(Long freightSettlementId) {
        List<TransportAbnormalOperation> operation=transportAbnormalOperationRepository.findByFreightSettlementIdAndStatusOrderByCreateTimeDesc(freightSettlementId,"1");
        TransportAbnormalOperationDto dto=transportAbnormalOperationlTodo.toDto(operation.get(0));
        List<TransportAbnormal> abnormals=transportAbnormalRepository.findByTransportAbnormalOperationId(dto.getTransportAbnormalOperationId());
        dto.setPhotos(abnormals);
        return new BaseResult(0,dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult AbnormalDispose(TransportAbnormalOperationDto para) {
        para.setCreateTime(new Date());
        transportAbnormalOperationRepository.save(transportAbnormalOperationlTodo.toEntity(para));
        //更新结算表状态
        FreightSettlement settlement=freightSettlementRepository.findById(para.getFreightSettlementId()).orElseGet(FreightSettlement::new);
        settlement.setAbnormalStatus("2".equals(para.getStatus())?"3":"4");
        if("2".equals(para.getStatus())){
            //处理完成 结算状态 改为已结算
            settlement.setStatus(3);
            settlement.setCleanDate(new Date());
        }
        freightSettlementRepository.save(settlement);
        //流程更新
        TransportTakeStatus status=transportTakeStatusRepository.findByTransportTakeCarriageId(settlement.getTransportTakeCarriageId());
        status.setDisposeTime(new Date());
        transportTakeStatusRepository.save(status);
        return new BaseResult(0,messageSource.getMessage("operation.success", null, Locale.CHINA));
    }

    @Override
    public BaseResult AbnormalDetil(Long freightSettlementId) {
        List<TransportAbnormalOperationDto> list=transportAbnormalOperationMapper.selectByFreightSettlementId(freightSettlementId);
        return new BaseResult(0,list);
    }

    @Override
    public BaseResult transportStatus(Long transportTakeCarriageId) {
        TransportTakeStatus status=transportTakeStatusRepository.findByTransportTakeCarriageId(transportTakeCarriageId);
        return new BaseResult(0,status);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updatePrice(FreightSettlementPrice para) {
        FreightSettlement settlement=freightSettlementRepository.findById(para.getFreightSettlementId()).orElseGet(FreightSettlement::new);
        para.setOldPrice(settlement.getPrice());
        para.setOldFreight(settlement.getFreight());
        para.setUpdateTime(new Date());
        para.setNewFreight(para.getNewFreight()==null?settlement.getFreight():para.getNewFreight());
        para.setNewPrice(para.getNewPrice()==null?settlement.getPrice():para.getNewPrice());

        if(para.getOldPrice().compareTo(para.getNewPrice())==0&&para.getOldFreight().compareTo(para.getNewFreight())==0){
            return new BaseResult(1,"费用没有变化,无需修改");
        }
        //先删除
        transportMapper.deletePrice(settlement.getFreightSettlementId());
        //计算差异费用
        BigDecimal diffFee=new BigDecimal(0);
        if(settlement.getDiffNum().compareTo(BigDecimal.ZERO)==1){
            diffFee=para.getNewPrice().multiply(settlement.getDiffNum());
        }
        settlement.setSettlementAmount(para.getNewFreight().multiply(settlement.getRealNum()).subtract(diffFee).subtract(settlement.getOtherFee()));
        settlement.setPrice(para.getNewPrice());
        settlement.setFreight(para.getNewFreight());
        settlement.setDiffPrice(diffFee);
        freightSettlementRepository.save(settlement);
        freightSettlementPriceRepository.save(para);
        //计算
        return new BaseResult(0,settlement);
    }

}
